package com.hefan.api.controller.notify;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.SmsCodeTypeEnum;
import com.cat.tiger.util.CollectionUtils;
import com.hefan.api.service.SmsLocalService;
import com.hefan.common.util.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lxw on 2016/9/28.
 */
@Controller
@RequestMapping("/v1/sms")
public class SmsController {

    public static Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Resource
    private SmsLocalService smsLocalService;

    /**
     * 发送短信验证码
     * @param request
     * @return
     */
    @RequestMapping("/send")
    @ResponseBody
    public String sendSms(HttpServletRequest request) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map smsMap = HttpUtils.initParam(request, HashMap.class);
            if(CollectionUtils.isEmpty(smsMap)
                    || !smsMap.containsKey("smsType") || !smsMap.containsKey("mobile")
                    || StringUtils.isBlank(String.valueOf(smsMap.get("mobile")))
            ) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }
            String mobile = String.valueOf(smsMap.get("mobile"));
            int smsType = Integer.valueOf(String.valueOf(smsMap.get("smsType"))).intValue();
            if(!SmsCodeTypeEnum.enumTypeIsExist(smsType)) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }
            //发送短信验证码
            resultBean = smsLocalService.sendSmsCode(smsType,mobile);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        }
        return JSON.toJSONString(resultBean);
    }

}
